package com.haojiang.mh.utils

import android.content.res.Resources
import android.util.DisplayMetrics
import java.lang.reflect.Field

object ScreenUtil {
    private var isInitMiui = false
    private var mTmpMetrics: Field? = null

    /**
     * 适应水平屏幕
     */
    fun adaptWidth(resources: Resources, designWidth: Int): Resources {
        val dm = getDisplayMetrics(resources)
        dm.xdpi = (dm.widthPixels * 72f) / designWidth
        val newXdpi: Float = dm.xdpi
        setAppDmXdpi(newXdpi)
        return resources
    }

    /**
     * 适应垂直屏幕
     */
    fun adaptHeight(resources: Resources, designHeight: Int): Resources {
        val dm = getDisplayMetrics(resources)
        dm.xdpi = (dm.heightPixels * 72f) / designHeight
        val newXdpi = dm.xdpi
        setAppDmXdpi(newXdpi)
        return resources
    }

    /**
     * 关闭适配
     */
    fun closeAdapt(resources: Resources): Resources {
        val dm = getDisplayMetrics(resources)
        dm.xdpi = dm.density * 72
        val newXdpi = dm.xdpi
        setAppDmXdpi(newXdpi)
        return resources
    }

    /**
     * pt 转 px
     */
    fun pt2Px(value: Float): Int {
        val dm = Resources.getSystem().displayMetrics
        return (value * dm?.xdpi!! / 72f + 0.5f).toInt()
    }

    /**
     * px 转 pt
     */
    fun px2Pt(value: Float): Int {
        val dm = Resources.getSystem().displayMetrics
        return (value * 72 / dm?.xdpi!! + 0.5).toInt()
    }

    /**
     * 修改水平dpi
     */
    private fun setAppDmXdpi(xdpi: Float) {
        Resources.getSystem().displayMetrics.xdpi = xdpi
    }

    /**
     * 获取DisplayMetrics
     */
    fun getDisplayMetrics(resources: Resources): DisplayMetrics {
        return getMiuiTmpMetrics(resources) ?: return resources.displayMetrics
    }

    /**
     * 适配Miui显示
     */
    fun getMiuiTmpMetrics(resources: Resources): DisplayMetrics? {
        if (!isInitMiui) {
            var ret: DisplayMetrics? = null
            val simpleName = resources.javaClass.simpleName
            if ("MiuiResources" == simpleName || "XResources" == simpleName) {
                try {
                    mTmpMetrics = Resources::class.java.getDeclaredField("mTmpMetrics")
                    mTmpMetrics?.isAccessible = true
                    ret = mTmpMetrics?.get(resources) as DisplayMetrics
                } catch (e: Exception) {
                    KLog.d("no field of mTmpMetrics in resources.")
                }
            }
            isInitMiui = true
            return ret
        }
        if (mTmpMetrics == null) return null
        return try {
            mTmpMetrics?.get(mTmpMetrics) as DisplayMetrics
        } catch (e: Exception) {
            null
        }
    }
}